package com.kakarote.bi.common.enums;

import cn.hutool.core.util.StrUtil;
import com.kakarote.core.common.enums.DateFilterEnum;

import javax.validation.constraints.NotNull;

/**
 * mysql时间格式化工具
 *
 * @author zhangzhiwei
 */
public enum BiMySqlDateEnum {
    /**
     * 格式化为本天
     */
    toDate("date(FIELD_NAME)"),
    /**
     * 格式化为本周
     */
    toMonday("DATE_FORMAT(date_sub(FIELD_NAME,INTERVAL WEEKDAY(FIELD_NAME) DAY),'%Y-%m-%d')"),
    /**
     * 格式化为本月
     */
    toStartOfMonth("DATE_FORMAT(DATE_ADD(FIELD_NAME,interval -day(FIELD_NAME)+1 day),'%Y-%m-%d')"),
    /**
     * 格式化为本季度
     */
    toStartOfQuarter("concat(date_format(LAST_DAY(MAKEDATE(EXTRACT(YEAR FROM  FIELD_NAME),1) + interval QUARTER(FIELD_NAME)*3-3 month),'%Y-%m-'),'01')"),
    /**
     * 格式化为本年
     */
    toYear("year(FIELD_NAME)"),
    ;

    /**
     * 默认的替换字段名称
     */
    private static final String FIELD_NAME = "FIELD_NAME";

    private final String value;

    BiMySqlDateEnum(String value) {
        this.value = value;
    }

    public String getValue() {
        return name();
    }

    /**
     * 获取商业智能默认格式化展示时间
     *
     * @param dateFilterEnum date
     * @return format
     */
    public static String getMySqlDate(DateFilterEnum dateFilterEnum) {
        switch (dateFilterEnum) {
            case QUARTER:
            case LAST_QUARTER:
            case NEXT_QUARTER:
            case YEAR:
            case LAST_YEAR:
            case NEXT_YEAR:
                return toStartOfMonth.getValue();
            default:
                return toDate.getValue();
        }
    }

    public static @NotNull String parseSql(String data, String fieldName) {
        if (StrUtil.isEmpty(data)) {
            return toDate.value.replace(FIELD_NAME, fieldName);
        }
        BiMySqlDateEnum dateEnum = BiMySqlDateEnum.valueOf(data);
        return dateEnum.value.replace(FIELD_NAME, fieldName);
    }
}
